//! # 消息总线错误处理
//!
//! 定义消息总线系统中的所有错误类型和错误处理机制

use std::fmt;
use thiserror::Error;

/// 消息总线错误类型
#[derive(Error, Debug, Clone)]
pub enum MessageBusError {
    /// 连接错误
    #[error("连接错误: {message}")]
    ConnectionError { message: String },

    /// 序列化错误
    #[error("序列化错误: {message}")]
    SerializationError { message: String },

    /// 反序列化错误
    #[error("反序列化错误: {message}")]
    DeserializationError { message: String },

    /// 消息发布错误
    #[error("消息发布失败: {topic}, 原因: {reason}")]
    PublishError { topic: String, reason: String },

    /// 消息订阅错误
    #[error("消息订阅失败: {pattern}, 原因: {reason}")]
    SubscribeError { pattern: String, reason: String },

    /// 消息接收错误
    #[error("消息接收错误: {reason}")]
    ReceiveError { reason: String },

    /// 配置错误
    #[error("配置错误: {field}, 值: {value}, 原因: {reason}")]
    ConfigError { field: String, value: String, reason: String },

    /// 路由错误
    #[error("消息路由错误: {topic}, 原因: {reason}")]
    RoutingError { topic: String, reason: String },

    /// 超时错误
    #[error("操作超时: {operation}, 超时时间: {timeout_ms}ms")]
    TimeoutError { operation: String, timeout_ms: u64 },

    /// 容量错误
    #[error("容量不足: {resource}, 当前: {current}, 最大: {max}")]
    CapacityError { resource: String, current: usize, max: usize },

    /// 权限错误
    #[error("权限不足: {operation}, 原因: {reason}")]
    PermissionError { operation: String, reason: String },

    /// 网络错误
    #[error("网络错误: {message}")]
    NetworkError { message: String },

    /// 内部错误
    #[error("内部错误: {message}")]
    InternalError { message: String },

    /// 不支持的操作
    #[error("不支持的操作: {operation}")]
    UnsupportedOperation { operation: String },

    /// 消息格式错误
    #[error("消息格式错误: {message}")]
    MessageFormatError { message: String },

    /// 重试次数超限
    #[error("重试次数超限: {operation}, 最大重试: {max_retries}")]
    RetryExhausted { operation: String, max_retries: u32 },

    /// 资源未找到
    #[error("资源未找到: {resource_type}={resource_id}")]
    NotFound { resource_type: String, resource_id: String },
}

impl MessageBusError {
    /// 创建连接错误
    pub fn connection_error(message: impl Into<String>) -> Self {
        Self::ConnectionError { message: message.into() }
    }

    /// 创建序列化错误
    pub fn serialization_error(message: impl Into<String>) -> Self {
        Self::SerializationError { message: message.into() }
    }

    /// 创建反序列化错误
    pub fn deserialization_error(message: impl Into<String>) -> Self {
        Self::DeserializationError { message: message.into() }
    }

    /// 创建发布错误
    pub fn publish_error(topic: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::PublishError { 
            topic: topic.into(), 
            reason: reason.into() 
        }
    }

    /// 创建订阅错误
    pub fn subscribe_error(pattern: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::SubscribeError { 
            pattern: pattern.into(), 
            reason: reason.into() 
        }
    }

    /// 创建接收错误
    pub fn receive_error(reason: impl Into<String>) -> Self {
        Self::ReceiveError { reason: reason.into() }
    }

    /// 创建配置错误
    pub fn config_error(
        field: impl Into<String>, 
        value: impl Into<String>, 
        reason: impl Into<String>
    ) -> Self {
        Self::ConfigError { 
            field: field.into(), 
            value: value.into(), 
            reason: reason.into() 
        }
    }

    /// 创建路由错误
    pub fn routing_error(topic: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::RoutingError { 
            topic: topic.into(), 
            reason: reason.into() 
        }
    }

    /// 创建超时错误
    pub fn timeout_error(operation: impl Into<String>, timeout_ms: u64) -> Self {
        Self::TimeoutError { 
            operation: operation.into(), 
            timeout_ms 
        }
    }

    /// 创建容量错误
    pub fn capacity_error(
        resource: impl Into<String>, 
        current: usize, 
        max: usize
    ) -> Self {
        Self::CapacityError { 
            resource: resource.into(), 
            current, 
            max 
        }
    }

    /// 创建权限错误
    pub fn permission_error(operation: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::PermissionError { 
            operation: operation.into(), 
            reason: reason.into() 
        }
    }

    /// 创建网络错误
    pub fn network_error(message: impl Into<String>) -> Self {
        Self::NetworkError { message: message.into() }
    }

    /// 创建内部错误
    pub fn internal_error(message: impl Into<String>) -> Self {
        Self::InternalError { message: message.into() }
    }
    
    /// 创建存储错误
    pub fn storage_error(message: impl Into<String>) -> Self {
        Self::InternalError { 
            message: format!("存储错误: {}", message.into())
        }
    }

    /// 创建不支持操作错误
    pub fn unsupported_operation(operation: impl Into<String>) -> Self {
        Self::UnsupportedOperation { operation: operation.into() }
    }

    /// 创建消息格式错误
    pub fn message_format_error(message: impl Into<String>) -> Self {
        Self::MessageFormatError { message: message.into() }
    }

    /// 创建重试超限错误
    pub fn retry_exhausted(operation: impl Into<String>, max_retries: u32) -> Self {
        Self::RetryExhausted { 
            operation: operation.into(), 
            max_retries 
        }
    }

    /// 创建资源未找到错误
    pub fn not_found(resource_type: impl Into<String>, resource_id: impl Into<String>) -> Self {
        Self::NotFound {
            resource_type: resource_type.into(),
            resource_id: resource_id.into(),
        }
    }

    /// 检查是否为可重试的错误
    pub fn is_retryable(&self) -> bool {
        match self {
            MessageBusError::ConnectionError { .. } => true,
            MessageBusError::NetworkError { .. } => true,
            MessageBusError::TimeoutError { .. } => true,
            MessageBusError::CapacityError { .. } => true,
            MessageBusError::InternalError { .. } => true,
            _ => false,
        }
    }

    /// 获取错误的严重程度
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            MessageBusError::ConfigError { .. } => ErrorSeverity::Critical,
            MessageBusError::PermissionError { .. } => ErrorSeverity::Critical,
            MessageBusError::UnsupportedOperation { .. } => ErrorSeverity::Critical,
            MessageBusError::SerializationError { .. } => ErrorSeverity::High,
            MessageBusError::DeserializationError { .. } => ErrorSeverity::High,
            MessageBusError::MessageFormatError { .. } => ErrorSeverity::High,
            MessageBusError::ConnectionError { .. } => ErrorSeverity::Medium,
            MessageBusError::NetworkError { .. } => ErrorSeverity::Medium,
            MessageBusError::PublishError { .. } => ErrorSeverity::Medium,
            MessageBusError::SubscribeError { .. } => ErrorSeverity::Medium,
            MessageBusError::TimeoutError { .. } => ErrorSeverity::Low,
            MessageBusError::CapacityError { .. } => ErrorSeverity::Low,
            MessageBusError::ReceiveError { .. } => ErrorSeverity::Low,
            MessageBusError::RoutingError { .. } => ErrorSeverity::Low,
            MessageBusError::InternalError { .. } => ErrorSeverity::Medium,
            MessageBusError::RetryExhausted { .. } => ErrorSeverity::High,
            MessageBusError::NotFound { .. } => ErrorSeverity::Medium,
        }
    }
}

/// 错误严重程度
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ErrorSeverity {
    Low = 1,
    Medium = 2,
    High = 3,
    Critical = 4,
}

impl fmt::Display for ErrorSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ErrorSeverity::Low => write!(f, "LOW"),
            ErrorSeverity::Medium => write!(f, "MEDIUM"),
            ErrorSeverity::High => write!(f, "HIGH"),
            ErrorSeverity::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// 消息总线结果类型
pub type MessageBusResult<T> = Result<T, MessageBusError>;

/// 从标准错误转换
impl From<std::io::Error> for MessageBusError {
    fn from(err: std::io::Error) -> Self {
        MessageBusError::network_error(err.to_string())
    }
}

impl From<serde_json::Error> for MessageBusError {
    fn from(err: serde_json::Error) -> Self {
        MessageBusError::serialization_error(err.to_string())
    }
}

impl From<tokio::time::error::Elapsed> for MessageBusError {
    fn from(_err: tokio::time::error::Elapsed) -> Self {
        MessageBusError::timeout_error("operation", 0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_creation() {
        let err = MessageBusError::connection_error("连接失败");
        assert!(matches!(err, MessageBusError::ConnectionError { .. }));
        assert!(err.is_retryable());
        assert_eq!(err.severity(), ErrorSeverity::Medium);
    }

    #[test]
    fn test_error_severity() {
        let config_err = MessageBusError::config_error("port", "invalid", "非数字");
        assert_eq!(config_err.severity(), ErrorSeverity::Critical);

        let timeout_err = MessageBusError::timeout_error("publish", 5000);
        assert_eq!(timeout_err.severity(), ErrorSeverity::Low);
    }

    #[test]
    fn test_retryable_errors() {
        assert!(MessageBusError::connection_error("test").is_retryable());
        assert!(MessageBusError::network_error("test").is_retryable());
        assert!(!MessageBusError::config_error("test", "test", "test").is_retryable());
    }
}